package cn.xsw.controller;


import cn.xsw.common.ResultBody;
import cn.xsw.entity.Appointment;
import cn.xsw.entity.vo.AppointmentVo;
import cn.xsw.service.AppointmentService;
import cn.xsw.service.impl.UserServiceImpl;
import cn.xsw.utils.BaseQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liangYiHui
 * @since 2021-06-05
 */
@RestController
@RequestMapping("/appointment")
@Api(tags = "预约接口")
public class AppointmentController {

    @Resource
    private AppointmentService appointmentService;
    @Resource
    private UserServiceImpl userService;

    @ApiOperation("分页条件查询")
    @GetMapping("/findPage")
    public ResultBody findPage(BaseQuery<Appointment> query){
        Page page = appointmentService.page(query.page());
        List<Appointment> records = page.getRecords();
        List<AppointmentVo> appointmentVos = new ArrayList<>();
        records.forEach(a->{
            AppointmentVo appointmentVo = new AppointmentVo();
            BeanUtils.copyProperties(a,appointmentVo);
            appointmentVo.setUser(userService.getById(a.getUid()));
            appointmentVos.add(appointmentVo);
        });
        page.setRecords(appointmentVos);
        return ResultBody.success().page(page);
    }


    @ApiOperation("根据id删除")
    @GetMapping("/delById/{id}")
    public ResultBody delById(@PathVariable("id") int id){
        Boolean b = appointmentService.removeById(id);
        if(!b) return ResultBody.error("删除失败");
        return ResultBody.success();
    }

    @ApiOperation("添加或更新（对象id为空：添加，对象id不为空：编辑）")
    @PostMapping("/saveOrUpdate")
    public ResultBody saveOrUpdate(@RequestBody Appointment appointment){
        Boolean b = appointmentService.saveOrUpdate(appointment);
        if(!b) return ResultBody.error("操作失败");
        return ResultBody.success();
    }
}

